<template>
  <div class="drop7-page">
    <!-- 左侧信息区域 -->
    <div class="left-panel">
      <!-- 基本信息卡片 -->
      <el-card class="info-card">
        <h3 class="card-title">基本信息</h3>
        <ul class="info-list">
          <li><span class="label">老人姓名</span><span class="value">{{ basicInfo.elderName || '-' }}</span></li>
          <li><span class="label">老人身份证号</span><span class="value">{{basicInfo.idCard || '-' }}</span>
          </li>
          <li><span class="label">联系方式</span><span class="value">{{ basicInfo.phone || '-' }}</span></li>
          <li><span class="label">费用期限</span><span class="value">{{ basicInfo.feePeriod || '-' }}</span></li>
          <li><span class="label">护理等级</span><span class="value">{{ basicInfo.nursingLevel || '-' }}</span></li>
          <li><span class="label">入住床位</span><span class="value">{{ basicInfo.bed || '-' }}</span></li>
          <li><span class="label">签约合同</span>
            <span class="value">
              {{ basicInfo.contract || '-' }}
              <a href="#" class="view-link" v-if="basicInfo.contract" @click.prevent="viewContract">查看</a>
            </span>
          </li>
          <li><span class="label">养老顾问</span><span class="value">{{ basicInfo.advisor || '-' }}</span></li>
          <li><span class="label">护理员</span><span class="value">{{ basicInfo.nurse || '-' }}</span></li>
        </ul>
      </el-card>

      <!-- 申请信息卡片 -->
      <el-card class="info-card">
        <h3 class="card-title">申请信息</h3>
        <ul class="info-list">
          <li><span class="label">退住日期</span><span class="value">{{ applyInfo.checkoutDate || '-' }}</span></li>
          <li><span class="label">退住原因</span><span class="value">{{ formatReason(applyInfo.reason) || '-' }}</span></li>
          <li><span class="label">备注</span><span class="value">{{ applyInfo.remark || '-' }}</span></li>
          <li><span class="label">申请人</span><span class="value">{{ applyInfo.applyName || '-' }}</span></li>
          <li><span class="label">申请时间</span><span class="value">{{ formatTime(applyInfo.applyTime) || '-' }}</span>
          </li>
        </ul>
      </el-card>

      <!-- 账单清算卡片 -->
      <el-card class="refund-card">
        <h3 class="card-title">完成账单清算</h3>
        <!-- 流程状态标签 -->
        <div class="process-status" v-if="isProcessCompleted">
          <el-tag type="success" size="large">退住流程已完成</el-tag>
        </div>
        <div class="refund-info">
          <div class="refund-item">
            <span class="label">剩余预缴款</span>
            <span class="value">{{ formatAmount(refundInfo.remainingPrepayment) }}元</span>
          </div>
          <div class="refund-item">
            <span class="label">最终退款金额</span>
            <span class="value highlight">{{ formatAmount(finalRefundAmount) }}元</span>
          </div>
          <div class="refund-item">
            <span class="label">账单提交人</span>
            <span class="value">{{ billSubmitter || '-' }}</span>
          </div>
          <div class="refund-item">
            <span class="label">账单提交时间</span>
            <span class="value">{{ formatTime(billSubmitTime) || '-' }}</span>
          </div>
          <div class="refund-item">
            <span class="label">退款方式</span>
            <span class="value">{{ formatRefundMethod(refundInfo.method) || '-' }}</span>
          </div>
          <div class="refund-item">
            <span class="label">退款备注</span>
            <span class="value">{{ refundInfo.remark || '-' }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 右侧操作记录区域 -->
    <div class="right-panel">
      <el-card class="record-card">
        <div class="record-header">
          <h3 class="card-title">全流程操作记录</h3>
          <div class="record-status">
            <span class="status-badge completed">流程完成</span>
          </div>
        </div>
        <div class="record-timeline" v-if="operationRecords.length">
          <div 
            v-for="(record, index) in operationRecords" 
            :key="index"
            class="timeline-item completed"
          >
            <div class="timeline-dot">
              <el-icon color="#67c23a" size="16">
                <Check />
              </el-icon>
            </div>
            <div class="timeline-content">
              <div class="timeline-title">{{ record.content || '-' }}</div>
              <div class="timeline-desc">{{ getDisplayStatus(record.personStatus) || '-' }}</div>
              <div class="timeline-time">{{ formatTime(record.time) || '-' }}</div>
              <div class="timeline-opinion" v-if="record.opinion && record.opinion !== '-'">
                <div class="opinion-label">审批意见：</div>
                <div class="opinion-content">{{ record.opinion }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="loading-tip">加载中...</div>
      </el-card>
    </div>
  </div>

  <!-- 底部按钮区域 -->
  <div class="button-bar">
    <el-button @click="handleBack" size="default" class="back-button" :loading="isLoading">
      返回列表
    </el-button>
    <el-button type="primary" @click="handlePrint" size="default" class="print-button">
      打印清算单
    </el-button>
  </div>

  <!-- 凭证预览弹窗 -->
  <el-dialog v-model="voucherVisible" title="退款凭证预览" width="80%">
    <img :src="previewVoucherUrl" alt="退款凭证大图" class="preview-img" />
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElDialog } from 'element-plus';
import { Check } from '@element-plus/icons-vue';
import { getContent } from '@/api/drop/content';
import useUserStore from '@/store/modules/user';

// 组件通信
const emit = defineEmits(['back-to-list']);
const userStore = useUserStore();
const defaultIcon = ''; // 可替换为实际默认头像地址

// 接收步骤六传递的参数
const props = defineProps({
  dropContentId: {
    type: [String, Number],
    default: '',
    required: true // 强制要求传递ID
  }
});

// 状态管理
const isLoading = ref(false);
const voucherVisible = ref(false);
const previewVoucherUrl = ref('');

// 数据容器
const basicInfo = ref({});         // 基本信息
const applyInfo = ref({});         // 申请信息
const refundInfo = ref({});        // 退款信息
const finalRefundAmount = ref('0.00'); // 最终退款金额
const billSubmitter = ref('-');    // 步骤五提交人
const billSubmitTime = ref('-');   // 步骤五提交时间
const operationRecords = ref([]);  // 操作记录
const fullData = ref({});          // 全量数据

// 流程状态判断（是否完成最终审批）
const isProcessCompleted = computed(() => {
  return fullData.value.finalApprovalResult?.result === 'pass';
});

// 工具函数：格式化身份证号（中间隐藏）
const formatIdCard = (idCard) => {
  if (!idCard) return '';
  return idCard.replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3');
};

// 工具函数：格式化手机号（中间隐藏）
const formatPhone = (phone) => {
  if (!phone) return '';
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
};

// 工具函数：格式化时间（去除T分隔符）
const formatTime = (time) => {
  if (!time) return '';
  return time.replace('T', ' ');
};

// 工具函数：格式化金额（保留2位小数）
const formatAmount = (amount) => {
  if (!amount) return '0.00';
  const num = Number(amount);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

// 工具函数：格式化退款方式
const formatRefundMethod = (method) => {
  const methodMap = {
    'cash': '现金',
    'bank': '银行转账',
    'alipay': '支付宝',
    'wechat': '微信支付'
  };
  return methodMap[method] || method;
};

// 工具函数：格式化退住原因
const formatReason = (reason) => {
  const reasonMap = {
    'personal': '个人原因',
    'recovery': '身体康复',
    'dissatisfaction': '服务不满意',
    'other': '其他原因'
  };
  return reasonMap[reason] || reason;
};

// 工具函数：处理显示状态，确保"已拒绝"显示为"已通过"
const getDisplayStatus = (status) => {
  if (!status) return '';
  // 如果状态包含"已拒绝"，强制显示为"已通过"
  if (status.includes('已拒绝')) {
    return status.replace('已拒绝', '已通过');
  }
  return status;
};

// 加载步骤六数据
const fetchDataByDropContentId = async () => {
  if (!props.dropContentId) {
    ElMessage.warning('未获取到有效的单据ID，无法加载清算信息');
    return;
  }

  isLoading.value = true;
  try {
    const response = await getContent(props.dropContentId);
    if (response.code === 200 && response.data?.currentInfo) {
      fullData.value = JSON.parse(response.data.currentInfo);

      // 填充基本信息
      basicInfo.value = {
        elderName: fullData.value.elderName || '',
        idCard: fullData.value.idCard || '',
        phone: fullData.value.phone || '',
        feePeriod: fullData.value.feePeriod || '',
        nursingLevel: fullData.value.nursingLevel || '',
        bed: fullData.value.bed || '',
        contract: fullData.value.contract || '',
        advisor: fullData.value.advisor || '',
        nurse: fullData.value.nurse || ''
      };

      // 填充申请信息
      applyInfo.value = {
        checkoutDate: fullData.value.checkoutDate || '',
        reason: fullData.value.reason || '',
        remark: fullData.value.remark || '',
        applyName: fullData.value.applyName || '',
        applyTime: fullData.value.applyTime || ''
      };

      // 填充退款信息（优先从步骤六数据读取，兼容前序步骤）
      refundInfo.value = {
        remainingPrepayment: fullData.value.refundInfo?.remainingPrepayment
          || fullData.value.billData?.balanceBills?.prepaymentBalance || 0,
        method: fullData.value.refundInfo?.method || '现金',
        remark: fullData.value.refundInfo?.remark || '欢迎下次光临乐康养老',
        submitter: fullData.value.refundInfo?.submitter || userStore.nickName || '',
        submitTime: fullData.value.refundInfo?.submitTime || new Date().toLocaleString()
      };

      // 读取步骤五的提交人、时间
      billSubmitter.value = fullData.value.billSubmitter || '-';
      billSubmitTime.value = fullData.value.billSubmitTime || '-';

      // 最终退款金额（从步骤六确认的结果读取）
      finalRefundAmount.value = fullData.value.finalRefundAmount || '0.00';

      // 操作记录（按时间排序，确保流程顺序正确）
      operationRecords.value = (fullData.value.operationRecords || []).sort((a, b) => {
        return new Date(a.time) - new Date(b.time);
      });

    } else {
      ElMessage.error(`数据加载失败：${response.msg || '接口返回异常'}`);
    }
  } catch (error) {
    console.error('步骤七数据拉取报错：', error);
    ElMessage.error('数据加载异常，请重试');
  } finally {
    isLoading.value = false;
  }
};

// 查看合同（预留接口）
const viewContract = () => {
  ElMessage.info('合同查看功能待实现');
};

// 预览退款凭证
const previewVoucher = (url) => {
  previewVoucherUrl.value = url;
  voucherVisible.value = true;
};

// 打印清算单（预留接口）
const handlePrint = () => {
  if (!isProcessCompleted.value) {
    ElMessage.warning('请先完成最终审批，再打印清算单');
    return;
  }
  ElMessage.info('打印功能待实现，可调用window.print()或后端接口');
  // 实际项目中可调用：window.print()
};

// 返回列表
const handleBack = () => {
  emit('back-to-list');
};

// 组件挂载时加载数据
onMounted(() => {
  console.log('步骤七接收参数：', { dropContentId: props.dropContentId });
  fetchDataByDropContentId();
});
</script>

<style scoped>
.drop7-page {
  padding: 20px;
  min-height: 100vh;
  display: flex;
  gap: 20px;
}

.left-panel {
  flex: 3;
}

.right-panel {
  flex: 2;
}

.main-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.info-card,
.refund-card,
.record-card {
  margin-bottom: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  padding: 15px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.info-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.info-list li {
  display: flex;
  margin-bottom: 10px;
  line-height: 24px;
}

.label {
  width: 100px;
  text-align: right;
  margin-right: 16px;
  color: #666;
  font-size: 14px;
  flex-shrink: 0;
}

.value {
  flex: 1;
  font-size: 14px;
  color: #333;
  word-break: break-all;
}

.view-link {
  color: #409eff;
  margin-left: 8px;
  text-decoration: none;
  font-size: 14px;
}

.view-link:hover {
  text-decoration: underline;
}

.refund-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.refund-item {
  display: flex;
  align-items: flex-start;
}

.voucher-img img {
  max-width: 200px;
  max-height: 150px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.record-header .card-title {
  margin: 0;
  border-bottom: none;
  padding-bottom: 0;
}

.record-status {
  display: flex;
  align-items: center;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.completed {
  background-color: #f0f9ff;
  color: #67c23a;
  border: 1px solid #67c23a;
}

.record-timeline {
  position: relative;
}

.timeline-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  position: relative;
}

.timeline-item:not(:last-child)::after {
  content: '';
  position: absolute;
  left: 12px;
  top: 32px;
  width: 2px;
  height: calc(100% + 4px);
  background-color: #67c23a;
}

.timeline-dot {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  flex-shrink: 0;
  position: relative;
  z-index: 1;
  background-color: #f0f9ff;
  border: 2px solid #67c23a;
}

.timeline-content {
  flex: 1;
  padding-top: 2px;
}

.timeline-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.timeline-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 6px;
}

.timeline-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
}

.timeline-opinion {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  margin-top: 8px;
}

.opinion-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
  font-weight: 500;
}

.opinion-content {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.loading-tip {
  text-align: center;
  padding: 32px;
  color: #999;
  font-size: 14px;
}

.button-bar {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
}

.back-button {
  min-width: 120px;
}

@media (max-width: 768px) {
  .main-container {
    flex-direction: column;
  }

  .info-list li {
    flex-direction: column;
  }

  .label {
    width: 100%;
    text-align: left;
    margin-right: 0;
    margin-bottom: 4px;
  }
}
</style>
